package mongodb

import (
	"fmt"
	"sync"

	"gopkg.in/mgo.v2"
)

var (
	url      string
	gsession *mgo.Session
	mu       sync.Mutex
)

func Connect(url_ string) error {
	mu.Lock()
	defer mu.Unlock()

	if url == "" {
		url = url_
	}

	var err error
	gsession, err = mgo.Dial(url)
	if err != nil {
		fmt.Printf("Connect MongoDB Failed %s\n", url)
		return err
	}

	if err = gsession.Ping(); err != nil {
		return err
	}
	fmt.Printf("Connect MongoDB success %s\n", url)
	return nil
}

func Reconnect() *mgo.Session {
	mu.Lock()
	defer mu.Unlock()

	for {
		if gsession != nil {
			if gsession.Ping() == nil {
				break
			}
			gsession.Close()
		}

		var err error
		gsession, err = mgo.Dial(url)
		if err != nil {
			fmt.Printf("Reconnect Failed %s, err: %s\n", url, err.Error())
		} else {
			fmt.Printf("Reconnect success %s\n", url)
		}
	}

	return GetSession()
}

func GetSession() *mgo.Session {
	return gsession.Copy()
}

func IsDup(e error) bool {
	return mgo.IsDup(e)
}
